package start
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	
	public class LoadingTool extends EventDispatcher
	{
		private var urlLoader:URLLoader = new URLLoader();
		private var sourceArray:Array;
		private var _total:int;
		
		public function LoadingTool(sourceArray:Array)
		{
			this.sourceArray = sourceArray;
			initLoader();
		}
		
		private function initLoader():void
		{
			urlLoader = new URLLoader();
			urlLoader.addEventListener(ProgressEvent.PROGRESS,onProgress);
			urlLoader.addEventListener(IOErrorEvent.IO_ERROR,onIOError);
		}
		
		private function onIOError(event:IOErrorEvent):void
		{
			trace(event.text);
		}
		
		private function onProgress(event:ProgressEvent):void
		{
			_total += event.bytesTotal;
			urlLoader.close();
			load();
		}
		
		public function load():void
		{
			if (sourceArray.length > 0)
			{
				var url:String = sourceArray.shift();
				if (url != "GanDengYan.swf")
				{
					url = "resource/" + url;
				}
				urlLoader.load(new URLRequest(url));
			}
			else
			{
				dispatchEvent(new Event(Event.COMPLETE));
				clear();
			}
		}
		
		public  function get total():int
		{
			return _total;
		}
		
		public function clear():void
		{
			urlLoader.removeEventListener(ProgressEvent.PROGRESS,onProgress);
			urlLoader.removeEventListener(IOErrorEvent.IO_ERROR,onIOError);
			urlLoader = null;
			sourceArray = null;
		}
	}
}